using ExpressesClass.BestApi.Utils;
using System;
using System.Collections.Generic;

namespace ExpressesClass.BestApi.Base
{
    public class Client
    {
        string url;
        string partnerKey;
        string partnerID;
        static string messageFormat = "XML";

        public Client(string URL, string PARTNERKEY, string PARTNERID, string MESSAGEFORMAT) {
            url = URL;
            partnerKey = PARTNERKEY;
            partnerID = PARTNERID;
            messageFormat = MESSAGEFORMAT;
        }

        public T execute<T> (BaseRequest baseRequest) where T : BaseResponse
        {
            string response = string.Empty;

            SignParams signparams = new SignParams();
			signparams.serviceType= baseRequest.obtainServiceType();
			signparams.bizData = MakeBizData(baseRequest);
			signparams.partnerKey = partnerKey;
			signparams.partnerID = partnerID;

           string signString = signparams.bizData + signparams.partnerKey;

            Dictionary<string, string> data = new Dictionary<string, string>();
			data.Add("serviceType",signparams.serviceType);
			data.Add("bizData",signparams.bizData);
			data.Add("partnerID",signparams.partnerID);
			data.Add("sign", SignUtil.MakeMd5Sign(signString));

            response = HttpPostUtil.DoPost(url, data);
            return response == null ? null : (T)baseRequest.makeResponse(response, messageFormat);
        }

        public static string MakeBizData(BaseRequest basequest)
        {
            if ("XML".Equals(messageFormat, StringComparison.InvariantCultureIgnoreCase))
            {
                string BizData = XmlUtils.objToXml(basequest);
                return "<?xml version=\"1.0\"?>" + "\n" + BizData;
            }
           return JsonParser.objToJson(basequest);
        }

    }
}
